import cv2
import numpy as np
from deepface import DeepFace
from tools.image_tools import *
import os

# 创建输出目录
output_dir = "output"
os.makedirs(output_dir, exist_ok=True)

if __name__ == '__main__':
    img_path = "angry.png"
    img_ndarray = image_path_to_ndarray(img_path)

    # 分析图片
    objs = DeepFace.analyze(
        img_path=img_ndarray,
        actions=['emotion'],
        detector_backend='opencv'  # 确保使用OpenCV检测器获取坐标
    )

    # 读取原始图片
    img = cv2.imread(img_path)

    for face in objs:
        # 获取最大概率的情绪
        dominant_emotion = face['dominant_emotion']

        # 获取人脸区域坐标
        region = face['region']
        x = region['x']
        y = region['y']
        w = region['w']
        h = region['h']

        # 绘制矩形框
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # 添加文字标注
        text = f"{dominant_emotion}"
        cv2.putText(img, text,
                    (x, y - 10),
                    cv2.FONT_HERSHEY_SIMPLEX,
                    0.9, (0, 255, 0), 2)

    # 保存结果图片
    output_path = os.path.join(output_dir, os.path.basename(img_path))
    cv2.imwrite(output_path, img)

    # 只输出最大情绪
    print("检测到的主要情绪:", [face['dominant_emotion'] for face in objs])